// BackplaneDetector.v
// Copyright 2006, Pico Computing, Inc.

//This module performs backplane detection. 
//>>>>> The directions of the bus are changed if a PC is not detected 'in time'. The delay is
//>>>>> 2^^DELAY_SIZE, and is calibrated so that DELAY_SIZE == 24 yeield 1/6 seconds delay. <<<<<
//>>>>> Even so, if the card is inserted too slowly it can fail catastrophically with the   <<<<<
//>>>>> drivers enabled in the wrong direction.                                             <<<<<

`include "PicoDefines.v"

module BackplaneDetector
  #(parameter DELAY_SIZE = 16)                 //Number of bits in the delay counter. Determines the delay time.
   (input CLOCK1,                              //200 MHz free running oscillator
   output reg BackplaneDetected=0,             //Returns 1 if a backplane is detected
   output reg DetectorBusy=1,                  //Returns 1 when busy
   output MASTEREN,                            //Master Transceiver Enable
   input DETECTOR);                            //Backplane Loopback Clock In

reg [DELAY_SIZE:0] Timer = 0;
wire SlowClock;                                //~3 Hz Clock

always @(posedge CLOCK1)
   if (Timer[DELAY_SIZE] == 0) Timer <= Timer + 1;

assign SlowClock = Timer[DELAY_SIZE];

always @(posedge SlowClock)                    //After 1/3 second this logic gets triggered
begin
   if (DetectorBusy == 1) DetectorBusy <= 0;	  
	BackplaneDetected <= ~DETECTOR;            //DETECTOR is high for PCs, and low for backplanes
end                                            //You should be able to just latch in DETECTOR, but ISE optimizes the whole module out

                                               //When MASTEREN is low the bus interface is enabled
assign MASTEREN = ~((DetectorBusy) || ((BackplaneDetected == `BACKPLANE_REQUIRED) && (~DetectorBusy)));

endmodule
